﻿/*
 * Created by SharpDevelop.
 * User: phtrung
 * Date: 9/24/2009
 * Time: 2:24 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using popLib;
using System.Data;
using System.IO;
using System.Diagnostics;

namespace QuickHandBrakeTranscoder
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		string bathFile = FileLib.getFullPath("QuickHandBrakeTranscoder.bat");
		string command = "HandBrakeCLI.exe -i \"{0}\" -t 1 -c 1 -o \"{1}\" -f mp4 -O  -w {2} -e x264 -S {3} -a 1 -E faac -B {5} -R {4} -6 dpl2 -D 1 -v \r\n";
		string prelog = "{0} \""+Program.writeLogKeyword+"Begin convert file {1}.\"\r\n";
		string endlog = "{0} \""+Program.writeLogKeyword+"Convert file {1} completed.\"\r\n\r\n";
		string beginline = "ECHO =========={0}==========\r\n";
		string dataFile = FileLib.getFullPath("Data.dat");
		
		DataTable items = DataLib.initDataTable( "Item [ #Source, Destination, MovieWith, FileSize, ConvertedSize, Samplerate, Bitrate ]" );
		FormLib.ExecuteDragAndDrop handleDragItem;
		
		popLib.TransparentForm bgForm;
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			bgForm = FormLib.setTransparentForm( this, 255, FormBackground.VistaBlueContainer, new TransparentFormOption() );
			
			dgv_item.DataSource = items;
			comboBox1.SelectedIndex = 1;
			
			handleDragItem = delegate(Control control, string[] files) {
				string destination;
				FileInfo fileinfo;
				foreach( string file in files ){
					if( ".avi.flv.wmv.mpg.mkv.".IndexOf( Path.GetExtension(file).ToLower()+"." ) >=0 ){
						destination = Path.GetFileNameWithoutExtension( file )+".mp4";
						fileinfo = new FileInfo(file);
						
						items.Rows.Add( (file+","+destination+",640,"+(fileinfo.Length/1024/1024)+","+(fileinfo.Length/1024/1024/2)+",24,48").Split(',') );
					}
				}				
			};
			
			FormLib.dragAndDrop( this, handleDragItem );
			FormLib.dragAndDrop( dgv_item, handleDragItem );
			
			loadFile();
			
			
		}
				
		//Gen bath file and convert		
		void Button1Click(object sender, EventArgs e)
		{
			genBathFile();
			
			if( checkBox1.Checked ){
				double secondLeft = ((dateTimePicker1.Value.Hour - DateTime.Now.Hour)*3600) +
									( ((dateTimePicker1.Value.Minute - DateTime.Now.Minute)*60) );
				if( secondLeft < 0 ){
					FormLib.alert( "Your selected period is over!" );
					return;
				}
				
				if( !FormLib.confirm("Are you going to convert file at ["+dateTimePicker1.Value.ToString("HH:mm")+"]?") ) return;
				WindowLib.killProcess( "CloseTimer" );
				Process.Start( "CloseTimer.exe", string.Format("{0} 0 \"{1}\"", Math.Abs(secondLeft), bathFile) );
								
			}else{
				// start batch file immediately
				if( !FormLib.confirm("Are you going to convert file right now?") ) return;			
				ProcessStartInfo info = new ProcessStartInfo( bathFile );
				info.CreateNoWindow = true;
				info.WorkingDirectory = FileLib.getFullPath("");
	 			Process.Start( info );
			}
 			saveFile();
		}
		
		//browse folder to save file
		void Button3Click(object sender, EventArgs e)
		{
			ReturnSet rs = FormLib.folderBrowser( Environment.SpecialFolder.Desktop, true );
			if( rs.Success ) txt_path.Text = rs.Result.ToString();			
		}
		
		//update state of path and browse button
		void ComboBox1SelectedIndexChanged(object sender, EventArgs e)
		{
			txt_path.Enabled = button3.Enabled = (comboBox1.SelectedIndex == 2);
		}
		
		//exit
		void Button2Click(object sender, EventArgs e)
		{
			this.Close();
		}
		
		//browse for file
		void Button4Click(object sender, EventArgs e)
		{
			ReturnSet rs  = FormLib.openFile( "Movie Files(*.avi;*.mpg;*.wmv)|*.avi;*.mpg;*.wmv|All Files(*.*)|*.*", null, true );
			if( rs.Success ){
				handleDragItem( this, (string[])rs.Result );

			}
		}
				
		//save data before close
		void MainFormFormClosing(object sender, FormClosingEventArgs e)
		{
			//this.Hide();
			//bgForm.Hide();
			saveFile();
		}
		
		
		#region Global Functions
		
		void genBathFile(){
			if( items.Rows.Count == 0 ) return;
			
			string batchContent = "", destination = "";
			foreach( DataRow row in items.Rows ){
				destination = row[1].ToString();
				if(comboBox1.SelectedIndex == 1 ) destination = Path.Combine( Path.GetDirectoryName(row[0]+""), destination );
				if(comboBox1.SelectedIndex == 2 && Directory.Exists(txt_path.Text) )
					destination = Path.Combine( txt_path.Text, destination );
				
				batchContent += string.Format( beginline, row[0] );
				batchContent += string.Format( prelog, Path.GetFileName(Application.ExecutablePath), row[0] );
				batchContent += string.Format( command, row[0], destination, row[2], row[4], row[5], row[6] );
				batchContent += string.Format( endlog, Path.GetFileName(Application.ExecutablePath), row[0] );
			}
			
			if( checkBox2.Checked ) batchContent += "\r\nshutdown -s\r\n";
			
			FileLib.writeFile( bathFile, batchContent );
		}
		
		
		void saveFile(){
			items.WriteXml( dataFile );
			
			if( config == null ) config = ProfileLib.initProfile( ProfileLib.ProfileType.Ini, configPath );
			
			config.setValue( section, configOptions.StartSchedule+"", checkBox1.Checked ? "1" : "0" );
			config.setValue( section, configOptions.ScheduleTime+"", dateTimePicker1.Value.Ticks+"" );
			config.setValue( section, configOptions.AutoShutdown+"", checkBox2.Checked ? "1" : "0" );
		}
		
		Profile config;
		string configPath = FileLib.getFullPath( "config.ini" );
		string section = "Setting";
		enum configOptions { StartSchedule, ScheduleTime, AutoShutdown }
		void loadFile(){
			if( File.Exists( dataFile ) )
			items.ReadXml( dataFile );
			
			if( config == null ) config = ProfileLib.initProfile( ProfileLib.ProfileType.Ini, configPath );
			checkBox1.Checked = config.getValue( section, configOptions.StartSchedule+"", "0" ) == "0" ? false : true;
			dateTimePicker1.Value = new DateTime( Convert.ToInt64( config.getValue( section, configOptions.ScheduleTime+"", "633955446000000000" ) ) );
			checkBox2.Checked = config.getValue( section, configOptions.AutoShutdown+"", "0" ) == "0" ? false : true;
		}
		
		
		#endregion
		
		
		
	}
}
